/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package scoutobahn.ui;

import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;

/**
 *
 * @author Florian
 */
public class AutoCompletionDocument extends PlainDocument  {
    private JComboBox<String> comboBox;
    private ComboBoxModel<String> model;
    // flag to indicate if setSelectedItem has been called
    // subsequent calls to remove/insertString should be ignored
    private boolean selecting = false;

    public AutoCompletionDocument(final JComboBox<String> documentComboBox) {
        this.comboBox = documentComboBox;
        model = comboBox.getModel();
    }

    @Override
    public void remove(final int offs, final int len)
            throws BadLocationException {
        // return immediately when selecting an item
        if (selecting) {
            return;
        }
        super.remove(offs, len);
    }

    @Override
    public void insertString(final int offs,
            final String str, final AttributeSet a)
            throws BadLocationException {
        // return immediately when selecting an item
        if (selecting) {
            return;
        }
        // insert the string into the document
        super.insertString(offs, str, a);
        // lookup and select a matching item
        Object item = lookupItem(getText(0, getLength()));
        setSelectedItem(item);
        // remove all text and insert the completed string
        super.remove(0, getLength());
        super.insertString(0, item.toString(), a);
        // select the completed part
        JTextComponent editor =
                (JTextComponent) comboBox.getEditor().getEditorComponent();
        editor.setSelectionStart(offs + str.length());
        editor.setSelectionEnd(getLength());
    }

    private void setSelectedItem(final Object item) {
        selecting = true;
        model.setSelectedItem(item);
        selecting = false;
    }
    private Object lookupItem(final String pattern) {
        // iterate over all items
        for (int i = 0, n = model.getSize(); i < n; i++) {
            Object currentItem = model.getElementAt(i);
            // current item starts with the pattern?
            if (currentItem.toString().startsWith(pattern)) {
                return currentItem;
            }
        }
        // no item starts with the pattern => return null
        return null;
    }
}
